<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2023/12/31} {22:09} 
 */

namespace wanghua\general_utility_tools_php\wechat;


use wanghua\general_utility_tools_php\http\Curl;
use wanghua\general_utility_tools_php\tool\Tools;

/**
 * 微信小程序相关功能
 *
 * Class Applet
 *
 * @package wanghua\general_utility_tools_php\wechat
 */
class Applet
{


    protected $wechatConfig = [];
    protected $access_token_path = '';//票据存储位置，必须且具有读写权限
    protected $access_token_file_name = '';//存储文件名
    public function __construct(array $wechatConfig,string $access_token_file_name='')
    {
        $root_path = Tools::get_root_path();
        $this->wechatConfig = $wechatConfig;//全局配置
        $this->access_token_file_name = $access_token_file_name;
        $this->access_token_path = $root_path.$wechatConfig['access_token_path'];//access_token票据存储位置

        if($this->access_token_file_name){
            $this->access_token_path = $this->access_token_path.'/'.$this->access_token_file_name;
        }else{
            $this->access_token_path = $this->access_token_path.'/access_token.txt';
        }

        if(!file_exists($wechatConfig['access_token_path'])){
            mkdir($wechatConfig['access_token_path'], 0777, true);
            file_put_contents($this->access_token_path,'');
        }


        $this->checkParams();

    }

    /**
     * desc：检查参数
     * author：wh
     * @throws \Exception
     */
    protected function checkParams(){
        if(empty($this->wechatConfig['appid'])){
            throw new \Exception('请设置appid');
        }
        if(empty($this->wechatConfig['app_secret'])){
            throw new \Exception('请设置app_secret');
        }

    }

    /**
     * desc：获取小程序码
     *
     * 返回图片Buffer
     *
     * 文档地址：https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
     *
     * @param $scene 必须，最大32个可见字符，只支持数字
     * @param string $page 非必须
     * @param array $other_params 非必须
     * @return array|bool|int|string
     * @throws \Exception
     */
    function getwxacodeunlimit($scene,$page='',$other_params=[]){

        try {

            $obj = new UserAuth($this->wechatConfig,$this->access_token_file_name);
            $access_token = $obj->getAccessToken();
            $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

            $params = [
                'scene'=>$scene,//必须
                //'access_token'=>$access_token//必须
            ];

            //非必须
            if($page){
                $params['page'] = $page;
            }
            //非必须
            if($other_params){
                //合并
                $params = array_merge($params,$other_params);
            }
            return Curl::curl_post_json_return_buffer($url,$params);
        }catch (\Exception $e){
            Tools::log_to_write_txt([
                'error'=>'小程序码获取错误'.$e->getMessage(),
                'input'=>input(),
                'error_info'=>$e->getTraceAsString(),
            ]);
            return Tools::set_fail('小程序码获取错误.'.$e->getMessage());
        }
    }


    /**
     * description：获取票据
     * author：wanghua
     */
    function getAccessToken(){

        $access_token = file_get_contents($this->access_token_path);
        //获取票据，并验证是否超时，保证票据有效（全局唯一）
        if(!trim($access_token)){
            return $this->getAccessTokenNow();//实时获取
        }else{
            //是否过期
            $exp = explode('==', $access_token);
            if(time() - $exp[1]*1 >= 6900){//允许提前5分钟刷新
                return $this->getAccessTokenNow();//实时获取
            }else{
                return $exp[0];
            }
        }
    }


    /**
     * description：实时获取【基础-非网页授权token】
     * author：wanghua
     */
    function getAccessTokenNow(){
        try{
            //实时获取
            $appid = $this->wechatConfig['appid'];
            $appsecret = $this->wechatConfig['app_secret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            $jsoninfo = json_decode($output, true);

            file_put_contents($this->access_token_path, $jsoninfo["access_token"].'=='.time());//永久保存
            return $jsoninfo["access_token"];
        }catch (\Exception $e){
            Tools::log_to_write_txt(['error_title'=>'[错误]获取票据出错:'.$e->getMessage(),'error_info'=>$e->getTraceAsString()]);
            return false;
        }
    }


}